import {defineStore} from "pinia";
import {useWebSocketStore} from "@/store/webSocket";
import router from "@/router";


export const useUserStore = defineStore('user', {
    persist: true,
    state: () => {
        return {
            userInfo: {} as IUserInfo,
            token: '',
            refreshToken: '',
        }
    },
    /**
     * 封装计算属性，有缓存功能
     */
    getters: {
        isLogin(state) {
            return state.userInfo.username === '' || !state.userInfo.username
        }
    },
    /**
     * 封装业务逻辑，修改state
     */
    actions: {
        logout() {
            this.userInfo = {
                id: '',
                avatar: '',
                username: '',
                role: ''
            }
            this.token = ''
            this.refreshToken = ''
            router.push('/pc/login')
        },
        setUserInfo(val: any) {
            this.userInfo = val
        },
        setToken(val: any) {
            this.token = val
        },
        setRefreshToken(val: any) {
            this.refreshToken = val
        },
        successLogin(userInfo: any, token: any, refreshToken: any) {
            this.userInfo = userInfo
            this.token = token
            this.refreshToken = refreshToken
            const webSocketStore = useWebSocketStore()
            webSocketStore.authenticationReq()
            router.push('/pc/home')
        },

    },
})
